package springinpractice.ch8.news.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.feed.AbstractRssFeedView;

import springinpractice.ch8.news.model.NewsItem;

import com.sun.syndication.feed.rss.Channel;
import com.sun.syndication.feed.rss.Description;
import com.sun.syndication.feed.rss.Item;

/*
 * Author       :       Willie Wheeler and John Wheeler
 * Book         :       'Spring In Practice' [Book written by Willie Wheeler and John Wheeler]
 */

public final class RssNewsFeedView extends AbstractRssFeedView {
	private String feedTitle;
	private String feedDesc;
	private String feedLink;
	
	
	// ========================================================================
	// Dependency injection methods
	// ========================================================================
	
	public void setFeedTitle(String feedTitle) {
		this.feedTitle = feedTitle;
	}
	
	public void setFeedDescription(String feedDesc) {
		this.feedDesc = feedDesc;
	}
	
	public void setFeedLink(String feedLink) {
		this.feedLink = feedLink;
	}
	
	
	// ========================================================================
	// Creation methods
	// ========================================================================
	
	@Override
	protected void buildFeedMetadata(
			Map model, Channel feed, HttpServletRequest request) {
		
		feed.setTitle(feedTitle);
		feed.setDescription(feedDesc);
		feed.setLink(feedLink);
	}
	
	@Override
	protected List<Item> buildFeedItems(
			Map model,
			HttpServletRequest request,
			HttpServletResponse response)
		throws Exception {
		
		@SuppressWarnings("unchecked")
		List<NewsItem> newsItems = (List<NewsItem>) model.get("newsItemList");
		
		// Build the list of feed items
		List<Item> feedItems = new ArrayList<Item>();
		for (NewsItem newsItem : newsItems) {
			Item feedItem = new Item();
			feedItem.setTitle(newsItem.getTitle());
			feedItem.setAuthor(newsItem.getAuthor());
			feedItem.setPubDate(newsItem.getDatePublished());
			feedItem.setLink(newsItem.getLink());
			
			Description desc = new Description();
			desc.setType("text/html");
			desc.setValue(newsItem.getDescription());
			feedItem.setDescription(desc);
			
			feedItems.add(feedItem);
		}
		
		return feedItems;
	}
}
